import java.util.Collection;
import java.util.Scanner;

/**
 * @author joncaddey
 * @version 1.0
 */
public class TerritoryAdjacenciesReader {

	protected void read(final Scanner the_scanner,
			final Collection<Territory> the_territories) {
		String line;
		while (the_scanner.hasNext()
				&& (line = the_scanner.nextLine().trim()).length() != 0) {

			Territory add_to = lookUp(the_territories, line.trim());
			if (add_to == null) {
				throw new IllegalArgumentException("\"" + line
						+ "\" is not recognized as a territory");
			}
			while (the_scanner.hasNext()
					&& (line = the_scanner.nextLine().trim()).length() != 0) {
				Territory to_add = lookUp(the_territories, line.trim());
				if (to_add == null) {
					throw new IllegalArgumentException("\"" + line
							+ "\" is not recognized as a territory");
				}
				add_to.addNeighbor(to_add);
			}
		}
	}

	private Territory lookUp(final Collection<Territory> the_territories,
			final String the_name) {
		// this isn't very good. should jsut have map instead.
		// probably doesn't matter.
		Territory territory = null;
		for (Territory t : the_territories) {
			if (t.getName().equals(the_name)) {
				territory = t;
				break;
			}
		}
		return territory;
	}
}
